<template>
  <a-drawer
    :title="title"
    :maskClosable="true"
    width="650"
    placement="right"
    :closable="true"
    @close="close"
    :visible="visible"
    style="overflow: auto; padding-bottom: 53px"
  >
    <a-input-search v-model="keyWord" style="margin-bottom: 1px" placeholder="请输入关键字按回车进行搜索" @search="onSearch" />
    <a-form v-if="treeData_ && treeData_.length">
      <a-tree
        checkable
        @check="onCheck"
        :checkedKeys="checkedKeys"
        :treeData="treeData_"
        @expand="onExpand"
        @select="onTreeNodeSelect"
        :selectedKeys="selectedKeys"
        :expandedKeys="expandedKeysss"
        :checkStrictly="checkStrictly"
        :replaceFields="replaceFields"
      >
        <span slot="hasDatarule" slot-scope="{ slotTitle, ruleFlag }">
          {{ slotTitle }}<a-icon v-if="ruleFlag" type="align-left" style="margin-left: 5px; color: red"></a-icon>
        </span>
      </a-tree>
    </a-form>
    <a-empty v-else description="暂无数据" style="margin-top: 10px;" />

    <div class="drawer-bootom-button">
      <!-- <a-dropdown style="float: left" :trigger="['click']" placement="topCenter">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="switchCheckStrictly(1)">父子关联</a-menu-item>
          <a-menu-item key="2" @click="switchCheckStrictly(2)">取消关联</a-menu-item>
          <a-menu-item key="3" @click="checkALL">全部勾选</a-menu-item>
          <a-menu-item key="4" @click="cancelCheckALL">取消全选</a-menu-item>
          <a-menu-item key="5" @click="expandAll">展开所有</a-menu-item>
          <a-menu-item key="6" @click="closeAll">合并所有</a-menu-item>
        </a-menu>
        <a-button> 树操作 <a-icon type="up" /> </a-button>
      </a-dropdown> -->
      <!-- <a-popconfirm title="确定放弃编辑？" @confirm="close" okText="确定" cancelText="取消"> -->
        <a-button style="margin-right: 0.8rem" @click="close">取消</a-button>
      <!-- </a-popconfirm> -->
      <a-button @click="handleSubmit" type="primary" :loading="loading">保存</a-button>
    </div>

    <role-datarule-modal ref="datarule"></role-datarule-modal>
  </a-drawer>
</template>

<script>
import { putAction, getAction } from '@/api/manage'
import RoleDataruleModal from '@/views/system/modules/RoleDataruleModal'
import { productMixins } from '@/views/productLibrary/mixins/productMixins'
export default {
  name: 'ProductLibraryCategoryGroupAuthorizeModal',
  components: {
    RoleDataruleModal,
  },
  mixins: [ productMixins ],
  data() {
    return {
      roleId: '',
      defaultCheckedKeys: [],
      checkedKeys: [],
      expandedKeysss: [],
      allTreeKeys: [],
      autoExpandParent: true,
      checkStrictly: false,
      title: '类目权限配置',
      visible: false,
      loading: false,
      selectedKeys: [],
      keyWord:'',
      treeData_ : [],
      halfCheckedKeys: [],
      leafData: [],
      url: {
        updateByCategoryGroupId: "/hzkj-product/product/productLibrary/categoryGroupCategory/updateByCategoryGroupId",
        queryById: "/hzkj-product/product/productLibrary/categoryGroup/queryById"
      }
    }
  },
  created(){
    this.loadData_();
  },
  methods: {
    onTreeNodeSelect(id) {
      // if (id && id.length > 0) {
      //   this.selectedKeys = id
      // }
      // this.$refs.datarule.show(this.selectedKeys[0], this.roleId)
    },
    onCheck(o, e) {
      this.halfCheckedKeys = e.halfCheckedKeys;//半选部分
      if (this.checkStrictly) {
        this.checkedKeys = o.checked
      } else {
        this.checkedKeys = o
      }
    },
    show(roleId) {
      this.treeData_ = [...this.treeData];
      this.roleId = roleId
      this.keyWord = ''
      this.visible = true
      this.queryById();
    },
    close() {
      this.reset()
      this.$emit('close')
      this.visible = false
    },
    onExpand(expandedKeys) {
      this.expandedKeysss = expandedKeys
      this.autoExpandParent = false
    },
    reset() {
      this.expandedKeysss = []
      this.checkedKeys = []
      this.defaultCheckedKeys = []
      this.loading = false
    },
    expandAll() {
      this.expandedKeysss = this.allTreeKeys
    },
    closeAll() {
      this.expandedKeysss = []
    },
    checkALL() {
      this.checkedKeys = this.allTreeKeys
    },
    cancelCheckALL() {
      //this.checkedKeys = this.defaultCheckedKeys
      this.checkedKeys = []
    },
    switchCheckStrictly(v) {
      if (v == 1) {
        this.checkStrictly = false
      } else if (v == 2) {
        this.checkStrictly = true
      }
    },
    handleCancel() {
      this.close()
    },
    handleSubmit(exit) {
      let that = this
      if(!(that.checkedKeys && that.checkedKeys.length)){
        that.$message.warning('请选择类目!');
        return;
      }
      let params = {
        categoryGroupId: that.roleId,
        categoryIdList: [...that.checkedKeys, ...that.halfCheckedKeys]
      }
      that.loading = true
      putAction(this.url.updateByCategoryGroupId ,params).then((res) => {
        if (res.success) {
          that.$message.success(res.message)
          that.close();
          this.$emit('ok');
        } else {
          that.$message.error(res.message)
        }
      }).finally(() => {
        that.loading = false
      })
    },
    //模糊查询
    onSearch(value) {
      this.treeData_ = value ? this.filterTreeData(value,this.treeData) : this.treeData
    },
    filterTreeData(value, arr) {
      let newArr=[]
      arr.forEach(element => {
        if(element.name.indexOf(value)>-1){
          newArr.push(element)
        }else{
          if(element.children && element.children.length > 0){
            let redata =this.filterTreeData(value,element.children)
            if(redata && redata.length > 0){
              let obj={
                ...element,
                children:redata
              }
              newArr.push(obj)
            }
          }
        }
      })
      return newArr
    },
    queryById(){
      getAction(this.url.queryById, { id: this.roleId }).then((res) => {
        if(res.success){
          let checkedKeys = (res.result && res.result.categoryList) || [];
          checkedKeys = checkedKeys.map(item => item.id);
          this.getLeafList(this.treeData_);
          this.checkedKeys = this.findCommonElements(checkedKeys, this.leafData);
          this.halfCheckedKeys = checkedKeys.filter(item => this.checkedKeys.indexOf(item) === -1);
        }else{
          this.$message.warning(res.message);
        }
      })
    },
    getLeafList(data){
      data.map((item) => {
        if(item.children && item.children.length > 0){
          this.getLeafList(item.children);
        }else {
          //leafData数组存放  
          this.leafData.push(item.id);
        }
      })
    },
    //获取两个数组中的公共元素
    findCommonElements(arr1, arr2) {
      return arr1.filter(item => arr2.includes(item));
    }
  }
}
</script>
<style lang="less" scoped>
.drawer-bootom-button {
  position: absolute;
  bottom: 0;
  width: 100%;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: right;
  left: 0;
  background: #fff;
  border-radius: 0 0 2px 2px;
}
</style>